package com.jthinker.base.utils;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chen.gang on 2014/11/22.
 */
public class BaseUtils
{

    public static String getSaltPassword(String raw, String salt)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(raw).append("{").append(salt).append("}");
        return encodeByMD5(sb.toString());
    }

    public static String encodeByMD5(String str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            return Hex.encodeHexString(messageDigest.digest());
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    public static Map<String, Object> getFailMessage(String message)
    {
        return getMessage(true, message, null);
    }

    public static Map<String, Object> getFailMessage(String message, Object data)
    {
        return getMessage(true, message, data);
    }

    public static Map<String, Object> getSuccessMessage(String message)
    {
        return getMessage(false, message, null);
    }

    public static Map<String, Object> getSuccessMessage(String message, Object data)
    {
        return getMessage(false, message, data);
    }

    public static Map<String, Object> getMessage(boolean isError, String message, Object data)
    {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("isError", isError);
        result.put("message", message);
        result.put("data", data);

        return result;
    }

    public static void main(String[] args)
    {
        System.out.println(getSaltPassword("admin", "admin"));
    }
}
